rm(list=ls())
library(tidyverse)

# Read correspondence table IBGE x SIAFI x UG (needed for Finbra 1997) ----
correspondence <- read_rds(here::here("data","processed","fiscalpolicy","correspondence_ibge_siafi_ug.rds"))
mun_codes_finbra_1997 <- read_csv(here::here("data","raw","FINBRA","csv","Finbra1997","UG97.csv")) 

# Check correspondence (all codes have a match)
mun_codes_not_joined <- mun_codes_finbra_1997 %>% 
  anti_join(correspondence, by = c("UG"="mun_ug")) 

# Check classification using names (all names match)
mun_codes <- mun_codes_finbra_1997 %>% 
  left_join(correspondence, by = c("UG"="mun_ug"))

mun_codes <- mun_codes %>% 
  mutate(NOME = stringi::stri_trans_general(NOME,"latin-ascii"),
         mun_name = stringi::stri_trans_general(NOME,"latin-ascii"),
         same_name = ifelse(NOME == mun_name, 1, 0)) %>% 
  filter(same_name == 0) 

# Read Finbras and create panel ------

# 1997 -----
for(y in 1997){
  plano_contas <- read_csv(here::here("data","raw","FINBRA","csv",paste0("Finbra",y),"Plano de Contas.csv")) 
  
  for(i in 1:5){
    chart <- read_csv(here::here("data","raw","FINBRA","csv",paste0("Finbra",y),paste0("Quadro",i,".csv"))) 
    assign(paste0("chart",i),chart)
    rm(chart)
  }

# Join all charts    
  finbra <- chart1 %>% 
    full_join(chart2, by = "UG") %>% 
    full_join(chart3, by = "UG") %>% 
    full_join(chart4, by = "UG") %>% 
    full_join(chart5, by = "UG") %>% 
    full_join(correspondence, by = c("UG" = "mun_ug")) %>% 
    relocate(UG,mun_name,mun_code_ibge)


  finbra <- finbra %>% 
    mutate(year = y) %>%
    rename(mun_code = mun_code_ibge) %>% 
    relocate(mun_code,year) %>%
    mutate_all(funs(replace(., is.na(.), 0))) 

  # Select variables
  finbra <- finbra %>%
    mutate(state_transf = T_ESTADOS,
           fed_transf = T_UNIAO) %>%
    rename(
      # Revenues
      current_revenues = REC_CORRE,
      capital_revenues = REC_CAPIT,
      tax_revenues = REC_TRIBUT.x,

      # Expenditures
      current_expenditures = D_CORRENTE,
      capital_expenditures = D_CAPITAL,
      personnel = D_PESSOAL,
      investments = INVESTIMEN,

      # Expenditures by function
      legislative = LEGISLATIVA,
      judiciary = JUDICIÁRIA,
      planning = PLANEJAMENTO,
      agriculture = AGRICULTURA,
      education_and_culture = EDUCAÇÃO_CULTURA,
      housing_and_urbanism = HABITAÇÃO_URBANISMO,
      industry_and_retail = INDUST_COMERC_SERVIÇOS,
      health_and_sanitation = SAUDE_SANEAMENTO,
      assistance_and_pension = ASSISTENCIA_PREVIDENCIA,
      transport = TRANSPORTE,
      policing = DEF_NAC_SEG_PÚBLICA,
      regional_development = DESENV_REGIONAL,
      energy_and_mineral_resources = ENERGIA_RECMINERAIS,
      comunication = COMUNICAÇÕES,
      labor = TRABALHO,
      other = OUTRAS_FUNÇÕES) %>%
    mutate(total_revenues = current_revenues + capital_revenues,
           total_expenditures = current_expenditures + capital_expenditures,
           total_funs = legislative + judiciary + planning + agriculture +
             education_and_culture + housing_and_urbanism + industry_and_retail +
             health_and_sanitation + assistance_and_pension + transport +
             policing + regional_development + energy_and_mineral_resources +
             comunication + other + labor,
           social_welfare_p = assistance_and_pension,
           social_welfare = NA,
           social_exp_p = health_and_sanitation + education_and_culture + social_welfare_p,
           social_exp = NA,
           nonsocial_exp_p = total_funs - social_exp_p,
           nonsocial_exp = NA,
           other_nonsocial_p = nonsocial_exp_p - housing_and_urbanism - transport,
           other_nonsocial = NA) %>%
    select(mun_code, year,
           # Revenues
           tot_rev = total_revenues,
           current_rev = current_revenues,
           capital_rev =  capital_revenues,
           tax_rev = tax_revenues,
           state_transf, fed_transf,

           # Expenditures
           tot_exp = total_expenditures,
           current_exp = current_expenditures,
           capital_exp = capital_expenditures,
           personnel,
           investments,

           # Functional Expenditures
           tot_funs = total_funs,
           health = health_and_sanitation,
           education = education_and_culture,
           welfare = social_welfare,
           welfare_p = social_welfare_p,
           social_exp,
           social_exp_p,
           nonsocial_exp,
           nonsocial_exp_p,
           housing = housing_and_urbanism,
           transport = transport,
           other = other_nonsocial,
           other_p = other_nonsocial_p)

  assign(paste0("finbra",y),finbra)
  rm(chart1,chart2,chart3,chart4,chart5,plano_contas,finbra,mun_codes,mun_codes_finbra_1997,mun_codes_not_joined,correspondence)
}

# 1998 to 2001 -----
 
for(y in 1998:2001){
  
  receita <- read_csv(here::here("data","raw","FINBRA","csv",paste0("Finbra",y),"Receita.csv")) 
  despesa <- read_csv(here::here("data","raw","FINBRA","csv",paste0("Finbra",y),"Despesa.csv")) 
  
  finbra <- receita %>% 
    left_join(despesa, by = c("CD_UF","CD_MUN")) %>% 
    mutate(mun_code=as.character(10000*CD_UF+CD_MUN),
           year = y) %>% 
    relocate(mun_code,year) %>%
    mutate_all(funs(replace(., is.na(.), 0)))
  
  # Select variables
  finbra <- finbra %>% 
    mutate(state_transf = `Transf Intergov do Estado` + `Rec Transf de Capital Estado`,
           fed_transf = `Transf Intergov da União` +  `Rec Transf de Capital União`) %>% 
    rename(
           # Revenues
           current_revenues = `Rec Correntes`,
           capital_revenues = `Rec de Capital`,
           tax_revenues = `Rec Tributária`,
           
           # Expenditures
           current_expenditures = `Desp Correntes`,
           capital_expenditures = `Despesas de Capital`,
           personnel = `Desp de Pessoal`,
           investments = `Investimentos`,
           
           # Expenditures by function
           legislative = `Legislativa`,
           judiciary = `Judiciária`,
           planning = `Planejamento`,
           agriculture = `Agricultura`,
           education_and_culture = `Educação e Cultura`,
           housing_and_urbanism = `Habitação e Urbanismo`,
           industry_and_retail = `Indústria e Comércio`,
           health_and_sanitation = `Saúde e Saneamento`,
           assistance_and_pension = `Assistência e Previdência`,
           transport = `Transporte`,
           policing = `Segurança Pública`,
           regional_development = `Desenvolvimento Regional`,
           energy_and_mineral_resources = `Energia e Recursos Minerais`,
           comunication = `Comunicações`,
           other = `Outras`) %>% 
      mutate(total_revenues = current_revenues + capital_revenues,
             total_expenditures = current_expenditures + capital_expenditures,
             total_funs = legislative + judiciary + planning + agriculture + 
               education_and_culture + housing_and_urbanism + industry_and_retail + 
               health_and_sanitation + assistance_and_pension + transport + 
               policing + regional_development + energy_and_mineral_resources + 
               comunication + other,
             social_welfare_p = assistance_and_pension,
             social_welfare = NA,
             social_exp_p = health_and_sanitation + education_and_culture + social_welfare_p,
             social_exp = NA,
             nonsocial_exp_p = total_funs - social_exp_p,
             nonsocial_exp = NA,
             other_nonsocial_p = nonsocial_exp_p - housing_and_urbanism - transport,
             other_nonsocial = NA) %>% 
    select(mun_code, year,
           # Revenues
           tot_rev = total_revenues,
           current_rev = current_revenues,
           capital_rev =  capital_revenues,
           tax_rev = tax_revenues,
           state_transf, fed_transf,
           
           # Expenditures
           tot_exp = total_expenditures,
           current_exp = current_expenditures,
           capital_exp = capital_expenditures,
           personnel,
           investments,
           
           # Functional Expenditures
           tot_funs = total_funs,
           health = health_and_sanitation,
           education = education_and_culture,
           welfare = social_welfare,
           welfare_p = social_welfare_p,
           social_exp,
           social_exp_p,
           nonsocial_exp,
           nonsocial_exp_p,
           housing = housing_and_urbanism,
           transport = transport,
           other = other_nonsocial,
           other_p = other_nonsocial_p)
  
  assign(paste0("finbra",y),finbra)
  rm(finbra,receita,despesa)
}


# 2002 and 2003  -----

for(y in 2002:2003){
  
  rec_desp <- read_csv(here::here("data","raw","FINBRA","csv",paste0("Finbra",y),"RecDesp.csv")) 
  
  finbra <- rec_desp %>%
    mutate(mun_code=as.character(10000*CD_UF+CD_MUN),
           year = y) %>%
    relocate(mun_code,year) %>%
    mutate_all(funs(replace(., is.na(.), 0)))
  
  # Select variables
  finbra <- finbra %>% 
    mutate(state_transf = `Transf Intergov Estado` + `Transf Convênios Estados DF` + `Transf Cap Inter Estados` + `Transf Cap Conv Estados`,
           fed_transf = `Transf Intergov da União` + `Transf Convênios União` + `Transf Cap Inter União` + `Transf Cap Conv União`) %>% 
    rename(
           # Revenues
           current_revenues = `Rec Correntes`,
           capital_revenues = `Rec de Capital`,
           tax_revenues = `Rec Tributária`,
           
           # Expenditures
           current_expenditures = `Desp Correntes`,
           capital_expenditures = `Despesas de Capital`,
           personnel = `Pessoal e Encarg Soc_PES`,
           investments = `Investimentos`,
           
           # Expenditures by function
           legislative = `Legislativa`, #1
           judiciary = `Judiciária`, #2 
           justice = `Essencial à Justiça`, #3
           administration = `Administração`, #4
           defense = `Defesa Nacional`, #5
           policing = `Segurança Pública`, #6
           int_relations = `Relações Exteriores`, #7
           social_assistance = `Assistência Social`, #8
           pension = `Previdência Social`, #9
           health = `Saúde`, #10
           labor = `Trabalho`, #11
           education = `Educação`, #12
           culture = `Cultura`, #13
           citizenship = `Direitos da Cidadania`, #14
           urbanism = `Urbanismo`, #15
           housing = `Habitação`, #16
           sanitation = `Saneamento`, #17
           environment = `Gestão Ambiental`, #18
           cience_and_tech = `Ciência e Tecnologia`, #19
           agriculture = `Agricultura`, #20
           agro_org = `Organização Agrária`, #21
           industry = `Indústria`, #22
           retail_and_services = `Comércio E Serviços`, #23
           comunication = `Comunicações`, #24
           resources = `Energia`, #25
           transport = `Transporte`, #26
           sports_and_leisure = `Desporto e Lazer`, #27
           special_attributions = `Encargos Especiais` #28
           ) %>% 
    mutate(total_revenues = current_revenues + capital_revenues,
           total_expenditures = current_expenditures + capital_expenditures,
           total_funs = legislative + judiciary + justice +
             administration + defense + policing+
             int_relations+ social_assistance+ pension+ health+
             labor+ education+ culture+ citizenship+urbanism+
             housing+ sanitation+ environment+ cience_and_tech +
             agriculture+ agro_org + industry + retail_and_services +
             comunication + resources + transport + sports_and_leisure +
             special_attributions,
           social_welfare_p = social_assistance + pension,
           social_welfare = social_assistance,
           health_and_sanitation = health + sanitation,
           education_and_culture = education + culture,
           social_exp_p = health_and_sanitation + education_and_culture + social_welfare_p,
           social_exp = health_and_sanitation + education_and_culture + social_welfare,
           nonsocial_exp_p = total_funs - social_exp_p,
           nonsocial_exp = total_funs - social_exp,
           housing_and_urbanism = housing + urbanism,
           other_nonsocial_p = nonsocial_exp_p - housing_and_urbanism - transport,
           other_nonsocial = nonsocial_exp - housing_and_urbanism - transport) %>% 
    select(mun_code, year,
           # Revenues
           tot_rev = total_revenues,
           current_rev = current_revenues,
           capital_rev =  capital_revenues,
           tax_rev = tax_revenues,
           state_transf, fed_transf,
           
           # Expenditures
           tot_exp = total_expenditures,
           current_exp = current_expenditures,
           capital_exp = capital_expenditures,
           personnel,
           investments,
           
           # Functional Expenditures
           tot_funs = total_funs,
           health = health_and_sanitation,
           education = education_and_culture,
           welfare = social_welfare,
           welfare_p = social_welfare_p,
           social_exp,
           social_exp_p,
           nonsocial_exp,
           nonsocial_exp_p,
           housing = housing_and_urbanism,
           transport = transport,
           other = other_nonsocial,
           other_p = other_nonsocial_p)
  
  assign(paste0("finbra",y),finbra)
  rm(finbra,rec_desp)
}


# 2004 to 2012 -----

for(y in 2004:2012){

  receita <- read_csv(here::here("data","raw","FINBRA","csv",paste0("Finbra",y),"Receita.csv")) 
  despesa <- read_csv(here::here("data","raw","FINBRA","csv",paste0("Finbra",y),"Despesa.csv")) 
  
  if (y == 2004) {
    desp_fun <- read_csv(here::here("data","raw","FINBRA","csv",paste0("Finbra",y),"DFuncao.csv")) %>% 
      rename(CD_UF = UF, CD_MUN = `Cod Mun`)
  } else {
    if (y == 2010){
      desp_fun <- read_csv(here::here("data","raw","FINBRA","csv",paste0("Finbra",y),"DSubFuncao.csv")) %>%  
      select_if(is.numeric)
    } else {
      desp_fun <- read_csv(here::here("data","raw","FINBRA","csv",paste0("Finbra",y),"DSubFuncao.csv"))
    }
    desp_fun <- desp_fun %>% 
      rename(CD_UF = UF, CD_MUN = `Cod Mun`)
  }
  
  finbra <- receita %>% 
    left_join(despesa, by = c("CD_UF","CD_MUN")) %>% 
    left_join(desp_fun, by = c("CD_UF","CD_MUN")) %>% 
    mutate(mun_code=as.character(10000*CD_UF+CD_MUN),
           year = y) %>% 
    relocate(mun_code,year) %>%
    mutate_all(funs(replace(., is.na(.), 0)))
  
  
  # Select variables
  finbra <- finbra %>% 
    mutate(state_transf = `Transf Intergov Estado` + `Transf Convênios Estados DF` +`Transf Cap Inter Estados` + `Transf Cap Conv Estados`,
           fed_transf = `Transf Intergov da União` + `Transf Convênios União` + `Transf Cap Inter União` + `Transf Cap Conv União`) %>% 
    rename(
           # Revenues
           current_revenues = `Rec Correntes`,
           capital_revenues = `Rec de Capital`,
           tax_revenues = `Rec Tributária`,
           
           # Expenditures
           current_expenditures = `Desp Correntes`,
           capital_expenditures = `Despesas de Capital`,
           personnel = `Pessoal e Encarg Soc_PES`,
           investments = `Investimentos`,
           
           # Expenditures by function
           legislative = `Legislativa`, #1
           judiciary = `Judiciária`, #2 
           justice = `Essencial à Justiça`, #3
           administration = `Administração`, #4
           defense = `Defesa Nacional`, #5
           policing = `Segurança Pública`, #6
           int_relations = `Relações Exteriores`, #7
           social_assistance = `Assistência Social`, #8
           pension = `Previdência Social`, #9
           health = `Saúde`, #10
           labor = `Trabalho`, #11
           education = `Educação`, #12
           culture = `Cultura`, #13
           citizenship = `Direitos da Cidadania`, #14
           urbanism = `Urbanismo`, #15
           housing = `Habitação`, #16
           sanitation = `Saneamento`, #17
           environment = `Gestão Ambiental`, #18
           cience_and_tech = `Ciência e Tecnologia`, #19
           agriculture = `Agricultura`, #20
           agro_org = `Organização Agrária`, #21
           industry = `Indústria`, #22
           retail_and_services = `Comércio e Serviços`, #23
           comunication = `Comunicações`, #24
           resources = `Energia`, #25
           transport = `Transporte`, #26
           sports_and_leisure = `Desporto e Lazer`, #27
           special_attributions = `Encargos Especiais` #28
    ) %>% 
    mutate(total_revenues = current_revenues + capital_revenues,
           total_expenditures = current_expenditures + capital_expenditures,
           total_funs = legislative + judiciary + justice +
             administration + defense + policing+
             int_relations+ social_assistance+ pension+ health+
             labor+ education+ culture+ citizenship+urbanism+
             housing+ sanitation+ environment+ cience_and_tech +
             agriculture+ agro_org + industry + retail_and_services +
             comunication + resources + transport + sports_and_leisure +
             special_attributions,
           social_welfare_p = social_assistance + pension,
           social_welfare = social_assistance,
           health_and_sanitation = health + sanitation,
           education_and_culture = education + culture,
           social_exp_p = health_and_sanitation + education_and_culture + social_welfare_p,
           social_exp = health_and_sanitation + education_and_culture + social_welfare,
           nonsocial_exp_p = total_funs - social_exp_p,
           nonsocial_exp = total_funs - social_exp,
           housing_and_urbanism = housing + urbanism,
           other_nonsocial_p = nonsocial_exp_p - housing_and_urbanism - transport,
           other_nonsocial = nonsocial_exp - housing_and_urbanism - transport) %>% 
    select(mun_code, year,
           # Revenues
           tot_rev = total_revenues,
           current_rev = current_revenues,
           capital_rev =  capital_revenues,
           tax_rev = tax_revenues,
           state_transf, fed_transf,
           
           # Expenditures
           tot_exp = total_expenditures,
           current_exp = current_expenditures,
           capital_exp = capital_expenditures,
           personnel,
           investments,
           
           # Functional Expenditures
           tot_funs = total_funs,
           health = health_and_sanitation,
           education = education_and_culture,
           welfare = social_welfare,
           welfare_p = social_welfare_p,
           social_exp,
           social_exp_p,
           nonsocial_exp,
           nonsocial_exp_p,
           housing = housing_and_urbanism,
           transport = transport,
           other = other_nonsocial,
           other_p = other_nonsocial_p)
 
  
  assign(paste0("finbra",y),finbra)
  rm(finbra,receita,despesa,desp_fun)
}

# Comment: The warning message happens due to problem in the original csv file for 2010.
# It does not affect the variables, but it creates a bunch of columns with missing vars. 

# 2013 and 2016 -----

for(y in 2013:2016){
  
  receita <- read_csv2(here::here("data","raw","FINBRA","csv",paste0("finbra",y,"_MUN_ReceitasOrcamentarias(AnexoI-C).csv")),
                       skip=4,col_names = c("Municipio","Codigo_IBGE","UF","Populacao","Tipo","Conta","Valor"),
                       local = locale(encoding = "latin1")) 
  
  despesa <- read_csv2(here::here("data","raw","FINBRA","csv",paste0("finbra",y,"_MUN_DespesasOrcamentarias(AnexoI-D).csv")),
                       skip=4,col_names = c("Municipio","Codigo_IBGE","UF","Populacao","Tipo","Conta","Valor"),
                       local = locale(encoding = "latin1")) 
  desp_fun <- read_csv2(here::here("data","raw","FINBRA","csv",paste0("finbra",y,"_MUN_DespesasporFuncao(AnexoI-E).csv")),
                        skip=4,col_names = c("Municipio","Codigo_IBGE","UF","Populacao","Tipo","Conta","Valor"),
                        local = locale(encoding = "latin1")) 
  
  finbra <- bind_rows(receita,despesa,desp_fun)
  
  if (y == 2013){
    finbra <- finbra %>% 
      filter(Tipo %in% c("Despesas Empenhadas","Receitas Realizadas"))  
  } else {
    finbra <- finbra %>% 
      filter(Tipo %in% c("Despesas Empenhadas","Receitas Brutas Realizadas"))
  }
  
  finbra <- finbra %>% 
    select(-Tipo) %>% 
    pivot_wider(names_from = Conta, values_from = Valor) %>% 
    mutate(year = y,
           mun_code = str_sub(Codigo_IBGE, 1, -2)) %>%
  mutate_all(funs(replace(., is.na(.), 0)))
  
  
  # Select variables
  finbra <- finbra %>% 
    mutate(state_transf = `1.7.2.2.00.00.00 - Transferências dos Estados` + `2.4.2.2.00.00.00 - Transferências dos Estados` + 
             `1.7.6.2.00.00.00 - Transferências de Convênios dos Estados e do Distrito Federal e de Suas Entidades` + 
             `2.4.7.2.00.00.00 - Transferências de Convênios dos Estados e do Distrito Federal e de suas Entidades`,
           fed_transf = `1.7.2.1.00.00.00 - Transferências da União` + `2.4.7.0.00.00.00 - Transferências de Convênios` + 
             `1.7.6.1.00.00.00 - Transferências de Convênios da União e de Suas Entidades` + 
             `2.4.7.1.00.00.00 - Transferências de Convênios da União e de suas Entidades`) %>% 
    rename(
           # Revenues
           current_revenues = `1.0.0.0.00.00.00 - Receitas Correntes`,
           capital_revenues = `2.0.0.0.00.00.00 - Receitas de Capital`,
           tax_revenues = `1.1.0.0.00.00.00 - Receita Tributária`,
           
           # Expenditures
           current_expenditures = `3.0.00.00.00.00 - Despesas Correntes`,
           capital_expenditures = `4.0.00.00.00.00 - Despesas de Capital`,
           personnel = `3.1.00.00.00.00 - Pessoal e Encargos Sociais`,
           investments = `4.4.00.00.00.00 - Investimentos`,
           
           # Expenditures by function
           legislative = `01 - Legislativa`, #1
           judiciary = `02 - Judiciária`, #2 
           justice = `03 - Essencial à Justiça`, #3
           administration = `04 - Administração`, #4
           defense = `05 - Defesa Nacional`, #5
           policing = `06 - Segurança Pública`, #6
           int_relations = `07 - Relações Exteriores`, #7
           social_assistance = `08 - Assistência Social`, #8
           pension = `09 - Previdência Social`, #9
           health = `10 - Saúde`, #10
           labor = `11 - Trabalho`, #11
           education = `12 - Educação`, #12
           culture = `13 - Cultura`, #13
           citizenship = `14 - Direitos da Cidadania`, #14
           urbanism = `15 - Urbanismo`, #15
           housing = `16 - Habitação`, #16
           sanitation = `17 - Saneamento`, #17
           environment = `18 - Gestão Ambiental`, #18
           cience_and_tech = `19 - Ciência e Tecnologia`, #19
           agriculture = `20 - Agricultura`, #20
           agro_org = `21 - Organização Agrária`, #21
           industry = `22 - Indústria`, #22
           retail_and_services = `23 - Comércio e Serviços`, #23
           comunication = `24 - Comunicações`, #24
           resources = `25 - Energia`, #25
           transport = `26 - Transporte`, #26
           sports_and_leisure = `27 - Desporto e Lazer`, #27
           special_attributions = `28 - Encargos Especiais` #28
    ) %>% 
    mutate(total_revenues = current_revenues + capital_revenues,
           total_expenditures = current_expenditures + capital_expenditures,
           total_funs = legislative + judiciary + justice +
             administration + defense + policing+
             int_relations+ social_assistance+ pension+ health+
             labor+ education+ culture+ citizenship+urbanism+
             housing+ sanitation+ environment+ cience_and_tech +
             agriculture+ agro_org + industry + retail_and_services +
             comunication + resources + transport + sports_and_leisure +
             special_attributions,
           social_welfare_p = social_assistance + pension,
           social_welfare = social_assistance,
           health_and_sanitation = health + sanitation,
           education_and_culture = education + culture,
           social_exp_p = health_and_sanitation + education_and_culture + social_welfare_p,
           social_exp = health_and_sanitation + education_and_culture + social_welfare,
           nonsocial_exp_p = total_funs - social_exp_p,
           nonsocial_exp = total_funs - social_exp,
           housing_and_urbanism = housing + urbanism,
           other_nonsocial_p = nonsocial_exp_p - housing_and_urbanism - transport,
           other_nonsocial = nonsocial_exp - housing_and_urbanism - transport) %>% 
    select(mun_code, year,
           # Revenues
           tot_rev = total_revenues,
           current_rev = current_revenues,
           capital_rev =  capital_revenues,
           tax_rev = tax_revenues,
           state_transf, fed_transf,
           
           # Expenditures
           tot_exp = total_expenditures,
           current_exp = current_expenditures,
           capital_exp = capital_expenditures,
           personnel,
           investments,
           
           # Functional Expenditures
           tot_funs = total_funs,
           health = health_and_sanitation,
           education = education_and_culture,
           welfare = social_welfare,
           welfare_p = social_welfare_p,
           social_exp,
           social_exp_p,
           nonsocial_exp,
           nonsocial_exp_p,
           housing = housing_and_urbanism,
           transport = transport,
           other = other_nonsocial,
           other_p = other_nonsocial_p)
  
  
  assign(paste0("finbra",y),finbra)
  rm(finbra,receita,despesa,desp_fun)
}

# Comment: The warning message happen because some municipalities report deductions using the negative sign "-". 
# This won't affect our variables also because we don't use deductions.
# The readr package already normalize the numbers to be positive.

# Create panel and save
finbra_list <- mget(ls(pattern = "finbra"))

finbra_panel <- bind_rows(finbra_list)

write_rds(finbra_panel, here::here("data","processed","fiscalpolicy","finbra_panel.rds"))
